﻿using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;

namespace CSharpHelpers.Contorls
{
    class DataGridHelper
    {
        /// <summary>
        /// 移除当前datagrid选中单元格的焦点
        /// </summary>
        /// <param name="dataGrid"></param>
        public static void RemoveCurrentCellFocus(DataGrid dataGrid)
        {
            var dr = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(0); //取第0行
            var presenter = GetVisualChild<DataGridCellsPresenter>(dr);
            var cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(1); //取第0列
            cell.Focus();
        }

        /// <summary>
        /// 获取可视化子对象
        /// 用于datagrid的某一单元格获取焦点
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="parent"></param>
        /// <returns></returns>
        public static T GetVisualChild<T>(Visual parent) where T : Visual
        {
            T child = default(T);
            int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < numVisuals; i++)
            {
                Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
                child = v as T;
                if (child == null)
                {
                    child = GetVisualChild<T>(v);
                }
                if (child != null)
                {
                    break;
                }
            }
            return child;
        }
    }
}
